package com.example.administrator.baikangxing.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.trace.LBSTraceClient;
import com.amap.api.trace.TraceListener;
import com.amap.api.trace.TraceLocation;
import com.example.administrator.baikangxing.Dao.OperateData;
import com.example.administrator.baikangxing.R;
import com.example.administrator.baikangxing.bean.TrailBean;
import com.example.administrator.baikangxing.config.Constants;
import com.example.administrator.baikangxing.config.Url;
import com.example.administrator.baikangxing.utils.CommomUtil;
import com.example.administrator.baikangxing.utils.HttpUtil;
import com.example.administrator.baikangxing.utils.ToastUtil;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/*轨迹*/
public class TrailActivity extends BaseActivity implements OnDateSelectedListener,TraceListener {
    private Polyline  mGraspPolyline;
    private Marker mGraspStartMarker, mGraspEndMarker;
    private MapView trail_map;
    private MaterialCalendarView trail_calendar;
    private AMap aMap;
    private ArrayList<TraceLocation> traceLocations;
    private LBSTraceClient mTraceClient;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        trail_map = findView(R.id.trail_map);
        trail_map.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = trail_map.getMap();
        }
    }

    @Override
    public int getContentViewLayoutId() {
        return R.layout.activity_trail;
    }

    @Override
    public void initView() {
        setTitles("历史轨迹");
        base_ib_menu.setVisibility(View.INVISIBLE);
        trail_calendar = findView(R.id.trail_calendar);
        mTraceClient = new LBSTraceClient(this.getApplicationContext());
    }

    @Override
    public void initListener() {
        trail_calendar.setOnDateChangedListener(this);
    }

    @Override
    public void initData() {
        traceLocations = new ArrayList<>();
    }

    @Override
    public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
        if(date.getMonth()<10){
            setMap(date.getYear()+"-0"+(date.getMonth()+1)+"-"+date.getDay());
        }else {
            setMap(date.getYear()+"-"+(date.getMonth()+1)+"-"+date.getDay());
        }
    }

    private void setMap(String date) {
        aMap.clear();
        traceLocations.clear();
        String url = Url.base_url+ Constants.HEALTH_TARGET[3];
        String select_num = OperateData.getStringData(this, Constants.SELECT_DEVICE_NUM);
        String[] values = new String[]{select_num,"day",date,date};
        HttpUtil.getInstance().postString(url, new String[]{"devid", "ext", "begin","end"}, values, new HttpUtil.CallBackPostString() {
            @Override
            public void onSuccess(JSONObject successString) {
                try {
                    if(successString.getString("errorCode").equals("0")){
                        JSONArray message = successString.getJSONArray("message");
                        ArrayList<TrailBean> trailBeen = CommomUtil.parserJsonArrayToList(message, TrailBean.class);
                        if(trailBeen.size() == 0){
                            ToastUtil.showToast("暂无数据");
                        }else {
                            for (int i = 0; i < trailBeen.size(); i++) {
                                if(trailBeen.get(i).getLat().equals("0")){
                                }else {
                                    TraceLocation traceLocation = new TraceLocation();
                                    traceLocation.setLatitude(Double.valueOf(trailBeen.get(i).getLat()));
                                    traceLocation.setLongitude(Double.valueOf(trailBeen.get(i).getLng()));
                                    traceLocations.add(traceLocation);
                                }
                            }
                            mTraceClient.queryProcessedTrace(1, traceLocations,
                                    LBSTraceClient.TYPE_AMAP,TrailActivity.this);
                        }
                    }else {
                        ToastUtil.showToast("暂无数据");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(JSONObject failString) {

            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {

            }
        });

    }

    @Override
    public void onRequestFailed(int i, String s) {

    }

    @Override
    public void onTraceProcessing(int i, int i1, List<LatLng> list) {

    }

    @Override
    public void onFinished(int i, List<LatLng> list, int i1, int i2) {
        Log.d("TAG", "onFinished");
        Toast.makeText(this.getApplicationContext(), "onFinished",
                Toast.LENGTH_SHORT).show();
        addGraspTrace(list);
    }

    /**
     * 地图上添加纠偏后轨迹线路及起终点
     *
     */
    private void addGraspTrace(List<LatLng> graspList) {
        if (graspList == null || graspList.size() < 2) {
            return;
        }
        LatLng startPoint = graspList.get(0);
        LatLng endPoint = graspList.get(graspList.size() - 1);
        mGraspPolyline = aMap.addPolyline(new PolylineOptions()
                .color(R.color.black)
                .width(10).addAll(graspList));
        mGraspStartMarker = aMap.addMarker(new MarkerOptions().position(
                startPoint).title("起点"));
        mGraspEndMarker = aMap.addMarker(new MarkerOptions()
                .position(endPoint).title("终点"));
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(graspList.get(0)));
    }
}
